//
//  NewsDetailViewController.m
//  jinneng
//
//  Created by mac on 2020/7/31.
//  Copyright © 2020 jznrj. All rights reserved.
//

#import "NewsDetailViewController.h"
#import <MJRefresh.h>
#import "JznWebView.h"
#import <Masonry.h>
#import "ColorUtil.h"
#import "URLUtil.h"
#import "JZNRequestUtil.h"
#import <MJExtension.h>
#import "LoginDto.h"
#import "PBFlatBarButtonItems.h"

#import "SizeUtil.h"
@interface NewsDetailViewController ()
@property(nonatomic, strong) JznWebView *jznWebView;
@property(nonatomic) long learnTime;
@property(nonatomic,strong) NSDate *inPageTime;
@property(nonatomic,strong) NSDate *startViewDate;
@property(nonatomic,strong) NSString *recordUrl;
@end

@implementation NewsDetailViewController

- (void)viewDidLoad {

    [super viewDidLoad];
    self.title = @"资料详情";
    UINavigationBar * bar = self.navigationController.navigationBar;
    UIImage *bgImage = [ColorUtil navigationBarColor:[ColorUtil titleColor] BarSize:bar.frame alphe:1.0];
    [bar setBackgroundImage:bgImage forBarMetrics:UIBarMetricsDefault];
    [bar setTintColor:[UIColor whiteColor]];
    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]}forState:UIControlStateNormal];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor,nil]];
    
    UIBarButtonItem *back = [PBFlatBarButtonItems backBarButtonItemWithTarget:self selector:@selector(goBack)];
    [self.navigationItem setLeftBarButtonItem:back];
    
    self.recordUrl = @"newsViewRecord/addNewsViewRecord";
    self.inPageTime = [[NSDate alloc]init];
    [self addJznWebView];
    [self postRetainNewsRecord];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kill:) name:@"UIApplicationWillTerminateNotification" object:nil];
    self.tabBarController.tabBar.frame = CGRectMake(0, 0, 0, 0);
    self.tabBarController.tabBar.hidden = YES;
    // Do any additional setup after loading the view.
    // Do any additional setup after loading the view.
}
-(void) viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = NO;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void) kill:(UIApplication *)application {
    
    NSDateFormatter *fmt = [[NSDateFormatter alloc]init];
    fmt.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    [fmt setDateStyle:NSDateFormatterMediumStyle];
    [fmt setTimeStyle:NSDateFormatterShortStyle];
    fmt.dateFormat = @"yyyy-MM-dd'T'hh:mm:ss.SSS'Z'";
    NSDate *now = [[NSDate alloc]init];
    NSString *startViewTime = [fmt stringFromDate:self.inPageTime];
    NSString *nowTime = [fmt stringFromDate:now];
    self.learnTime = [now timeIntervalSince1970] - [self.inPageTime timeIntervalSince1970];
    
    NSMutableDictionary *dictionary =  [NSJSONSerialization JSONObjectWithData:[self.params dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
    NSString *loginDtoJson = [[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"];
    LoginDto *loginDto = [LoginDto mj_objectWithKeyValues:loginDtoJson];
    [dictionary setObject:[NSString stringWithFormat:@"%d",loginDto.departmentId] forKey:@"departmentId"];
    [dictionary setObject:[NSString stringWithFormat:@"%d",loginDto.userId] forKey:@"userId"];
    [dictionary setObject:[NSString stringWithFormat:@"%li",self.learnTime] forKey:@"learnTime"];
    [dictionary setObject:startViewTime forKey:@"startViewTime"];
    [dictionary setObject:nowTime forKey:@"endViewTime"];
    [dictionary setObject:self.recordUrl forKey:@"url"];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:dictionary forKey:@"news_record"];
    
}


-(void) postRetainNewsRecord{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *newsRecord = [userDefaults objectForKey:@"news_record"];
    if (newsRecord!=nil) {
        NSString *url = [NSString stringWithFormat:@"%@/%@" ,[URLUtil hostName],newsRecord[@"url"]];
        [JZNRequestUtil requestUrl:url requestParams:newsRecord success:^(DataResult *dataResult) {
            
        } failure:^(NSError *error) {
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:newsRecord forKey:@"news_record"];
        }];
    }
}
-(void) goBack{
    NSDate *now = [[NSDate alloc]init];
    self.learnTime = [now timeIntervalSince1970] - [self.inPageTime timeIntervalSince1970];
    NSMutableDictionary *dictionary =  [NSJSONSerialization JSONObjectWithData:[self.params dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
    NSDateFormatter *fmt = [[NSDateFormatter alloc]init];
    fmt.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    [fmt setDateStyle:NSDateFormatterMediumStyle];
    [fmt setTimeStyle:NSDateFormatterShortStyle];
    fmt.dateFormat = @"yyyy-MM-dd'T'hh:mm:ss.SSS'Z'";
    
    NSString *startViewTime = [fmt stringFromDate:self.inPageTime];
    NSString *nowTime = [fmt stringFromDate:now];
    
    NSString *loginDtoJson = [[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"];
    LoginDto *loginDto = [LoginDto mj_objectWithKeyValues:loginDtoJson];
    [dictionary setObject:[NSString stringWithFormat:@"%d",loginDto.departmentId] forKey:@"departmentId"];
    [dictionary setObject:[NSString stringWithFormat:@"%d",loginDto.userId] forKey:@"userId"];
    [dictionary setObject:[NSString stringWithFormat:@"%li",self.learnTime] forKey:@"learnTime"];
    [dictionary setObject:startViewTime forKey:@"startViewTime"];
    [dictionary setObject:@"1" forKey:@"newsType"];
    [dictionary setObject:[fmt stringFromDate: [[NSDate alloc]init]] forKey:@"endViewTime"];
    
    [JZNRequestUtil requestUrl:[NSString stringWithFormat:@"%@/%@" ,[URLUtil hostName],self.recordUrl]
                 requestParams:dictionary
                       success:^(DataResult *dataResult) {
                           NSLog(@"success");
                       } failure:^(NSError *error) {
                           
                       }];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void) addJznWebView{
    [self.view addSubview:self.jznWebView];
    self.jznWebView.scrollView.bounces = NO;
    [self.jznWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    [self.jznWebView loadLocalFile:@"/ios_jinneng/newsDetail" type:@"html"];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    NSString *newsDetailUrl = [NSString stringWithFormat:@"%@/newsView/findNewsById",[URLUtil hostName]];
    NSString *detailJsString = [NSString stringWithFormat:@"getNewsDetail(\"%@\",%@)",newsDetailUrl,[self params]];
   // [self.jznWebView stringByEvaluatingJavaScriptFromString: detailJsString];
    [self.jznWebView evaluateJavaScript:detailJsString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
        
    }];
}



@end

